import os
import urllib

from google.appengine.ext import blobstore
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

import re,datetime
import datastore,library

facilityname=""
facilityid=""

class FileBlob:
     checked = ""
     theBlob = ""
     filename = ""
     date = ""



class MainHandler(webapp.RequestHandler):
    def Writeln(self,d):
        self.response.out.write(d )
        self.response.out.write("\n" )

    def post(self):
        self.Writeln("posted ..")

        blob_key =  self.request.get('theBlob')
        self.Writeln('theBlob =' + blob_key)

        blob_reader = blobstore.BlobReader(blob_key)
        playerlist= []                           # List to hold members
        regphone = re.compile("([\d]*)-([\d]*)-([\d]*)",re.IGNORECASE )

        facilityid = 3483 # SCTC

        for line in blob_reader:
           if( re.match("Last",line)): 
                print "skipping Last <<"
                continue

           if( re.search("Updated",line,re.IGNORECASE)): 
                print "skipping Updated <<"
                continue

           print "!!!!!"+ line + "@@@@\n<br>"
           u = line.rsplit(",")                  # Split the line delimited by ,
           print "***"+ str(u[3])+ "***"

           r = [ n.strip(" \r\n") for n in u ]   # Strip out end whitepace (includes \r\n )

           if( len(r) < 3): continue

# read data from spreadsheet

           index=1           # index is to account for new first column (
           skip=r[0]
           last = r[index+0]
           first = r[index+1]
           address = r[index+2] 
           city = r[index+3]
           zip = r[index+4]
           hphone = r[index+5]
           wphone = r[index+6]
           rating = r[index+7]
           email = r[index+8]
           email = email.strip("@")

#          Membership Year
           year = "2011"
           if( re.search("\*",last,re.IGNORECASE) ): 
             print "found *"
             year  = "2011"
           elif( re.search("#",last,re.IGNORECASE ) ): 
             print "found #"
             year  = "2012"
           else: 
             print "<br>"+ "*"*50 + "<br>"
             print "Skipping " + first + " " + last 
             print "<br>"+ "*"*50 + "<br>"
             continue


#          Last name ( strip out *#)
           last = last.strip("*#")

#          City (fix up Santa Clara errors )
           if(re.search("clara",city,re.IGNORECASE)): city = "Santa Clara"

#          Add .0 to rating if necessary
           rating = rating.strip(" ")
           if(len(rating) == 1): rating  = rating+".0"

#          Fix phone (unlikely)
#          mhome = regphone.findall( hphone )
#          mwork = regphone.findall( wphone )


           g = datastore.Membership( key_name= str(facilityid)+"_"+first+"_"+last )
           g.facility= int(facilityid)
           g.first = first
           g.last = last
           g.year = int(year)
           g.address = address
           g.email = email
           g.url = ""
           g.city = city
           g.zip = zip
           g.rating = rating
           playerlist.append( g )

           print( last,first,year,email,city,zip,rating)
           print( "<br>")

#       Put everyone in at the same time
        db.put( playerlist )




    def get(self):

        filter="sctc|roster"
        upload_url = blobstore.create_upload_url('/upload')
        files=[]
        chk="checked"
        for b in blobstore.BlobInfo.gql("order by creation desc"):

           if( re.search(filter, b.filename, re.IGNORECASE) == None): continue
 
           pac_time   = b.creation  - datetime.timedelta(hours=8)
           day = re.match( "([\d]{4}-[\d]{1,2}-[\d]{1,2})" , str(pac_time) )
           hr = re.search( "([\d]{2}:[\d]{2}:[\d]{2})" , str(pac_time) )

           date = day.group(0) + " " + hr.group(0)

           fb = FileBlob()
           fb.checked = chk
           fb.filename = b.filename
           fb.key = str(b.key())
           fb.date = date
           chk = ""
           files.append( fb)


        template_values = {
               'Upload_URL'   : upload_url,
               'Files'        : files,
               'Club'         : "SCTC"
        }

        path = os.path.join(os.path.dirname(__file__), 'display_loader.html')
        self.response.out.write(template.render(path, template_values))



class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):

    def post(self):
        self.response.out.write('post')



class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, blob_key):
       blob_key = str(urllib.unquote(blob_key))
 
       if not blobstore.get(blob_key):
            self.error(404)
       else:
            self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)


def main():
    application = webapp.WSGIApplication(
          [  ('/loadsctc', MainHandler),  
             ('/upload', UploadHandler),

          ], debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
  main()
